<!-- 
	* 摘要：用户管理
	* 软件名称：雪克码数据管理系统1.0
	* 文件名: userList.vue
	* 版本：1.0
 -->
<template>
	<div class="sn-common-container ">
		<div class="prcoss-container">
			<header>
				<div class="sn-flex sn-row-center hidden-sm-and-down">
					<el-select v-model="isDelete" value-key="" placeholder="是否删除" @change="currentChange(1)" style="width: 120px;margin-right: 10px;" clearable filterable >
						<el-option :label="'全部'" :value="'all'"></el-option>
						<el-option :label="'已删除'" :value="true"></el-option>
						<el-option :label="'未删除'" :value="false"></el-option>
					</el-select>
					<el-input v-model="searchValue" placeholder="输入用户昵称筛选" style="width: 200px" clearable
						@keyup.enter.native="currentChange(1)" />
					<el-input v-model="searchRealname" placeholder="输入用户真实姓名筛选" style="width: 200px;margin-left: 10px;"
						clearable @keyup.enter.native="currentChange(1)" />
					<el-input v-model="searchPhone" placeholder="输入用户手机号筛选" style="width: 200px;margin-left: 10px;"
						clearable @keyup.enter.native="currentChange(1)" />
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-search"
						@click="currentChange(1)">
						搜索
					</el-button>
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-plus"
						@click="addUserDialog = true">
						新建用户
					</el-button>
				</div>
				<div class="hidden-sm-and-up">
					<el-input v-model="searchValue" placeholder="输入用户昵称筛选" style="width: 200px" clearable
						@keyup.enter.native="currentChange(1)" />
					<el-button style="margin-left: 4px" type="primary" class="sn-btn" icon="el-icon-search"
						@click="currentChange(1)">
					</el-button>
					<el-button style="margin-left: 4px" type="primary" class="sn-btn" 
						@click="addUserDialog = true">
						新增
					</el-button>
				</div>
			</header>
			<section>
				<global-table :loading="tableLoading" style="margin-top: 20px;" :pageIndex="currentPage"
					:pageSize="pageSize" :headerData="initData" :data="tabelData" :isFullScreen="false" :operateW="450">
					<template #realname="scope">
						{{  scope.row.realPeopleConfirmed?scope.row.realname:'未实名' }}
					</template>
					<template #operate="scope">
						<div >
							<span  v-if="scope.row.isDeleted === true">
								<el-button type="primary" size="mini" @click="resetDeleteFn(scope.row.id)">恢复正常</el-button>
								<el-button type="primary" size="mini" class="sn-btn" @click="delStaffFn(scope.row.id,true)">彻底删除</el-button>
							</span>
							<span v-else>
								<!-- <el-button type="primary" size="mini" @click="lookUserOpen(scope.row)">查看</el-button> -->
								<el-button type="danger" v-if="scope.row.realPeopleConfirmed"  size="mini" @click="cancelRealPeopleFn(scope.row.id)">取消实名</el-button>
								<el-button type="warning" v-else size="mini" @click="openRealPeople(scope.row.id)">实名认证</el-button>
								<el-button type="primary" size="mini" icon="el-icon-lock"
									@click="lockOrUnlockFn(scope.row)">{{ scope.row.isLock ? '解锁' : '锁定' }}</el-button>
								<el-button type="warning"  size="mini" v-if="!scope.row.isEmployee"
									@click="addClickFn(scope.row)">添加至员工</el-button>
								<el-button type="primary" class="sn-btn"   icon="el-icon-delete" size="mini"
									@click="delStaffFn(scope.row.id,false)">删除</el-button>
							</span>
						</div>
					</template>
				</global-table>
			</section>
			<footer style="margin-top: 20px;">
				<el-pagination @current-change="currentChange" :current-page.sync="currentPage" :page-size="pageSize"
					layout="prev, pager, next, jumper" :pager-count="7" class="sn-pagination" hide-on-single-page
					style="text-align: center;" :total="totalNum" background>
					>
				</el-pagination>
			</footer>
		</div>
		<!-- 新增用户弹窗 -->
		<el-dialog :visible.sync="addUserDialog" class="sn-default-dialog" width="360px" @close="addUserDialogClose()">
			<div class="sn-title" slot="title">新增用户</div>
			<div v-loading="addUserLoading">
				<p style="margin-top: 0;">用户昵称：</p>
				<el-input v-model="addUserName" placeholder="请输入用户昵称" style=""></el-input>
				<p>用户手机号：</p>
				<el-input v-model="addUserPhone" placeholder="请输入用户手机号" style=""></el-input>
				<p>用户头像：</p>
				<el-upload
				class="upload-demo"
				ref="upload"
				action="/"
				:on-change="handleChange"
				:before-upload="beforeAvatarUpload"
				:file-list="fileList" 
				:limit="1"
				v-if="headimgResourceId === ''||!headimgResourceId"
				:auto-upload="false">
				<el-button slot="trigger" size="small" type="primary">选取图片</el-button>
				</el-upload>
				<div class="avatar-image" v-else>
					<el-image :src="headImg" style="height:100%;width:100%;display:block;margin:0;border:0;"></el-image>
					<span class="layer-black">
						<span
							class="layer-icon"
							@click="handlePictureCardPreview()"
						>
							<i class="el-icon-zoom-in"></i>
						</span>
						<span
							class="layer-icon"
							style="margin-left:5px;"
							@click="handlePictureCardRemove()"
						>
							<i class="el-icon-delete"></i>
						</span>
					</span>
				</div>
				<p style="text-align: center;">
					<el-button type="primary" size="medium" class="sn-btn" @click="addUserFn()">保存</el-button>
					<el-button size="medium" @click="addUserDialog = false">取消</el-button>
				</p>
			</div>
		</el-dialog>
		<!-- 添加到员工弹窗 -->
		<el-dialog :visible.sync="addStaffDialog" class="sn-default-dialog" width="360px" @close="addStaffDialogClose()">
			<div class="sn-title" slot="title">添加到员工</div>
			<div v-loading="addUserLoading">
				<p style="margin-top: 0;">员工名称：</p>
				<el-input v-model="editStaffName" placeholder="请输入员工名称" style=""></el-input>
				<p>员工手机号：</p>
				<el-input v-model="editStaffPhone" placeholder="请输入员工手机号" style=""></el-input>
				<p style="text-align: center;">
					<el-button type="primary" size="medium" class="sn-btn" @click="addUserToStaffFn()">保存</el-button>
					<el-button size="medium" @click="addStaffDialog = false">取消</el-button>
				</p>
			</div>
		</el-dialog>
		<!-- 查看用户 -->
		<el-dialog :visible.sync="lookUserDialog" class="sn-default-dialog" width="360px" @close="lookUserDialogClose()">
			<div class="sn-title" slot="title">查看用户详情</div>
			<div>
				<p style="margin-top: 0;">用户昵称：{{ userInfo.nickname || '未设置' }}</p>
				<p style="margin-top: 0;">真实姓名：{{ userInfo.realname || '未设置' }}</p>
				<p style="margin-top: 0;">手机号码：{{ userInfo.phoneNumber || '未设置' }}</p>
				<p style="margin-top: 0;">是否实名：{{ userInfo.realPeopleConfirmed ? '已实名' : '未实名' }}</p>
				<p style="margin-top: 0;">身份证号：{{ userInfo.idCardNo || '未设置' }}</p>
				<div class="sn-flex">
					<p style="margin-top: 0;">用户头像：</p>
					<div>
						<el-upload
						class="upload-demo"
						ref="upload"
						action="/"
						:on-change="handleChange"
						:before-upload="beforeAvatarUpload"
						:file-list="fileList" 
						:limit="1"
						v-if="!headimgResourceId&&!headImg"
						:auto-upload="false">
						<el-button slot="trigger" size="small" type="primary">选取图片</el-button>
						</el-upload>
						<div  v-else class="sn-flex">
							<div class="avatar-image">
								<el-image :src="headImg" style="height:100%;width:100%;display:block;margin:0;border:0;"></el-image>
								<span class="layer-black">
									<span
										class="layer-icon"
										@click="handlePictureCardPreview()"
									>
										<i class="el-icon-zoom-in"></i>
									</span>
									<span
										class="layer-icon"
										style="margin-left:5px;"
										@click="handlePictureCardRemove()"
									>
										<i class="el-icon-delete"></i>
									</span>
								</span>
							</div>
							<!-- <el-button type="primary" size="small" @click="">保存</el-button> -->
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
		<!-- 实名认证弹窗 -->
		<el-dialog :visible.sync="realPeopleDialog" class="sn-default-dialog" width="360px" @close="realPeopleDialogClose()">
			<div class="sn-title" slot="title">实名认证</div>
			<div v-loading="realLoading">
				<global-upload  :isIdcard="true"  :key="'front+dasda'" v-if="realPeopleDialog"
					:isIdcardFront="true" @imageUpload="idcardUpload" @imageRemove="idcardRemove"
					:initOne="realPeopleInfo.idCardFrontResourceId" :isHeadImg="true">
				</global-upload>
				<p>用户名称：</p>
				<el-input v-model="realPeopleInfo.realname" placeholder="请输入用户真实姓名" style=""></el-input>
				<p>身份证号：</p>
				<el-input v-model="realPeopleInfo.idCardNo" placeholder="请输入用户身份证号" style=""></el-input>
				<p style="text-align: center;">
					<el-button type="primary" size="medium" class="sn-btn" @click="realPeopleFn()">保存</el-button>
					<el-button size="medium" @click="realPeopleDialog = false">取消</el-button>
				</p>
			</div>
		</el-dialog>
		<CropperImage ref="cropperImage" @handleUploadSuccess="handleUploadSuccess" />
		<el-dialog :visible.sync="dialogVisible" :modal="false">
          <img width="100%" :src="headImg" alt="" />
        </el-dialog>
	</div>
</template>
  
<script>
import GlobalTable from '@/components/GlobalTable';
import { AddEmployee } from '@/api/accessmanage';
import {RestoreDeleteData} from '@/api/user'
import GlobalUpload from '@/components/GlobalUpload';
import { SearchUsersPage, GetUser, LockOrUnlock, ManualAddUser, DeleteUser,uploadAvatar,ModifyHeadImg,ManualRealPeopleConfirm,MngUpdateMyHeadImgAndRealName} from '@/api/user'
import { guid } from '@/utils'
import CropperImage from '@/components/CropperImage'
export default {
	components: { GlobalTable, GlobalUpload,CropperImage},
	data() {
		return {
			dialogVisible:false,
			fileList:[],
			tableLoading: false,
			tabelData: [],
			initData: [
				{
					label: '用户头像',
					value: 'headImg',
					id: guid(),
					type: 'img',
					imgStyle: {
						width: '50px',
						height: '50px'
					},
					width:100
				},
				{
					label: '用户昵称',
					value: 'nickname',
					id: guid(),
				},
				{
					label: '真实姓名',
					value: 'realname',
					id: guid(),
					isCustom: true,
					width:100
				},
				{
					label: '手机号',
					value: 'phoneNumber',
					id: guid(),
					width:120
				},
				{
					label: '注册时间',
					value: 'createdTime',
					id: guid(),
					width: 200
				},
			],
			currentPage: 1,
			pageSize: 10,
			totalNum: 0,
			searchValue: '',
			searchRealname: '',
			searchPhone: '',
			addUserDialog: false,
			editStaffName: '',
			editStaffPhone: '',
			addUserName: '',
			addUserPhone: '',
			addUserLoading: false,
			lookUserDialog: false,
			userInfo: {},
			addStaffDialog:false,
			chooseUserId:'',
			headimgResourceId:'',
			headImg:'',
			isLookHeadFlag:false,
			isDelete:false,
			realPeopleInfo:{	
				id:'',
				realPeopleConfirmed:true
			},
			realLoading:false,
			realPeopleDialog:false,
		}
	},
	created() {
		this.getDataListFn();
	},
	methods: {
		resetDeleteFn(id){
			this.$confirm('您确定要将该用户恢复？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await RestoreDeleteData({ id: id,type:'user' });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '恢复成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('恢复失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},
		handleChange(res) {
			this.$refs.cropperImage.handleOpen(res, { autoCropWidth: 108, autoCropHeight: 108 }, { type: 'fixed', sizeWidth: 108, sizeHeight: 108 })
		},
		handlePictureCardPreview(){
			this.dialogVisible = true;
		},
		handlePictureCardRemove(){
			this.headimgResourceId ='';
			this.headImg='';
			this.fileList = [];
		},
		beforeAvatarUpload(file) {
			const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
			const isJPG = whiteList.indexOf(fileSuffix) === -1;
			const isLt2M = file.size / 1024 / 1024 < 5;
			const whiteList = ["png", "jpg", "bmp", "PNG", "JPG","BMP",'jpeg','JPEG'];
			if (isJPG) {
				this.$message.error('上传图片只能是 png,jpg,bmp,jpeg格式的');
			}
			if (!isLt2M) {
			this.$message.error('上传头像图片大小不能超过 5MB!');
			}
			return isJPG && isLt2M;
		},
		async handleUploadSuccess(val) {
			let formData = new FormData()
     		formData.append('file', val, 'avatar.jpg');
			const res = await uploadAvatar(formData);
			if(res.code === 200){
				if(this.isLookHeadFlag){
					// const result = await ModifyHeadImg({resourceId:res.data[0].id});
					const result = await MngUpdateMyHeadImgAndRealName({userId:this.chooseUserId,headImgResource:{id:res.data[0].id}});
					
					if(result.code === 200){
						this.headimgResourceId = res.data[0].id;
						this.headImg = res.data[0].url;
					}else{
						this.$message.error(result.erroMessage);
					}
				}else{
					this.headimgResourceId = res.data[0].id;
					this.headImg = res.data[0].url;
				}
			}else{
				this.$message.error(res.erroMessage);
			}
		},
		
		//   分类icon上传成功
		userUploadFn(val){
			this.headimgResourceId = val.local;
	 	},
		//   分类icon删除
		userRemoveFn(val){
			this.headimgResourceId = '';
		},
		delStaffFn(id,isDelted) {
			let msg = isDelted?'彻底删除':'删除';
			this.$confirm('您将要'+msg+'该用户, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await DeleteUser({ userId: id,Thoroughly:isDelted  });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('删除失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 打开实名认证弹窗
		openRealPeople(id){
			this.chooseUserId = id;
			this.realPeopleDialog = true;
		},
		// 身份证号上传成功
		idcardUpload(val){
			this.realPeopleInfo.idCardFrontResourceId = val.local;
		},
		idcardRemove(){
			this.realPeopleInfo.idCardFrontResourceId = '';
		},
		// 实名认证弹窗关闭
		realPeopleDialogClose(){
			this.realPeopleInfo = {
				id:'',
				realPeopleConfirmed:true
			};
			this.realPeopleDialog = false;
		},
		// 用户实名认证
		async realPeopleFn(){
			this.realLoading = true;
			this.realPeopleInfo.id = this.chooseUserId;
			if(this.realPeopleInfo.realName === ''){
				this.$message.error('请输入姓名');
				this.realLoading = false;
				return;
			}
			let res = await ManualRealPeopleConfirm(this.realPeopleInfo);
			this.realLoading = false;
			if (res.code === 200) {
				this.$message({
					type: 'success',
					message: '实名认证成功!'
				});
				this.realPeopleDialog = false;
				this.getDataListFn();
			} else {
				this.$message.error('实名认证失败，错误信息：' + res.erroMessage);
			}
		},
		// 取消用户实名
		async cancelRealPeopleFn(id){
			this.$confirm('您确定要取消该用户的实名认证吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await ManualRealPeopleConfirm({ id: id,realPeopleConfirmed:false  });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '取消成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('取消失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消修改'
				});
			});
		},
		//   打开查看用户信息弹窗
		lookUserOpen(data) {
			this.userInfo = data;
			console.log(data);
			this.headImg = data.headImg;
			this.headimgResourceId = data.headimgResourceId;
			this.chooseUserId = data.id;
			this.isLookHeadFlag = true;
			this.lookUserDialog = true;
		},
		lookUserDialogClose(){
			this.headImg = '';
			this.headimgResourceId='';
			this.isLookHeadFlag = false;
		},
		//解锁或锁定用户
		async lockOrUnlockFn(user) {
			this.tableLoading = true;
			try {
				let res = await LockOrUnlock({ id: user.id });
				this.tableLoading = false;
				if (res.code === 200) {
					this.$message.success('锁定用户成功，该用户已被限制使用！');
					this.getDataListFn()
				} else {
					this.$message.error('锁定用户失败，错误信息：' + res.erroMessage);
				}
			} catch (error) {
				this.tableLoading = false;
				this.$message.error("请求服务器错误，错误信息：" + error);
			}
		},
		//新建用户
		async addUserFn() {
			this.addUserLoading = true; 
			if(this.addUserName === ''){
				this.addUserLoading = false;
				this.$message.error('请输入用户名！');
				return false;
			}
			if(this.addUserPhone === ''){
				this.addUserLoading = false;
				this.$message.error('请输入手机号！');
				return false;
			}
			if(this.headimgResourceId=== ''){
				this.addUserLoading = false;
				this.$message.error('请上传头像！');
				return false;
			}
			let params = {
				nickName: this.addUserName,
				phoneNumber: this.addUserPhone,
				headimgResourceId:this.headimgResourceId
			}
			let res = await ManualAddUser(params);
			this.addUserLoading = false;
			if (res.code === 200) {
				this.$message.success('新增用户成功');
				this.addUserDialog = false;
				this.getDataListFn();
			} else {
				this.$message.error('新增用户失败，错误信息：' + res.erroMessage)
			}
		},
		// 关闭新增用户信息窗口
		addUserDialogClose() {
			this.addUserName = '';
			this.addUserPhone = '';
			this.headImg = '';
			this.headimgResourceId = '';
			this.addUserLoading = false;
		},
		// 关闭新增员工窗口
		addStaffDialogClose() {
			this.editStaffName = '';
			this.editStaffPhone = '';
			this.addUserLoading = false;
		},
		// 添加到员工按钮点击
		addClickFn(data){
			this.addStaffDialog = true;
			this.chooseUserId = data.id;
		},
		// 添加用户到员工
		async addUserToStaffFn(data) {
			this.tableLoading = true;
			let params = { 
				userId: this.chooseUserId,
				employeeName: this.editStaffName,
				mobile:this.editStaffPhone
			}
			const res = await AddEmployee(params);
			this.tableLoading = false;
			if(res.code === 200){
				this.$message.success('添加成功');
				this.addStaffDialog = false;
				this.getDataListFn();
			}else{
				this.$message.error('添加失败，错误信息：' + res.erroMessage);
			}
		},
		//   分页器变化
		currentChange(val) {
			this.currentPage = val;
			this.getDataListFn();
		},
		//获取用户列表
		async getDataListFn() {
			this.tableLoading = true;
			let params = {
				pageIndex: this.currentPage,
				pageSize: this.pageSize,
				Nickname: this.searchValue,
				PhoneNumber: this.searchPhone,
				RealName: this.searchRealname
			}
			if(this.isDelete !=='all'){
				params.IsDeleted = this.isDelete;
			}
			const res = await SearchUsersPage(params);
			this.tableLoading = false;
			if (res.code === 200) {
				this.tabelData = res.data.list;
				this.totalNum = res.data.totalCount;
			} else {
				this.tabelData = [];
				this.$message.error('获取员工列表失败，错误信息：' + res.erroMessage);
			}
		},
	}
};
</script>
  
<style lang="scss" scoped>
.prcoss-container {
	box-sizing: border-box;
	padding: 20px;
	background-color: #fff;
}
.avatar-image{
	position: relative;
	list-style:none;
	margin-right: 5px;
	overflow: hidden;
	background-color: #fff;
	border: 1px solid #c0ccda;
	border-radius: 6px;
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	width: 98px;
	height: 98px;
	margin: 0 8px 8px 0;
	display: inline-block;
	.layer-black {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
		cursor: default;
		text-align: center;
		color: #fff;
		opacity: 0;
		font-size: 20px;
		background-color: rgba(0,0,0,.5);
		-webkit-transition: opacity .3s;
		transition: opacity .3s;
		&:hover {
			opacity: 1;
		}
	}
	.layer-black::after {
		display: inline-block;
		content: "";
		height: 100%;
		vertical-align: middle;
	}
}
</style>